package fr.enseirb.webxml.servlet;

import java.io.IOException;
import java.util.Properties;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import fr.enseirb.webxml.data.xml.XMLMediator;
import fr.enseirb.webxml.util.XMLToolkit;

import fr.enseirb.webxml.util.ServletToolkit;

/**
 * Servlet implementation class DefaultServlet
 */
public class CreateUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public CreateUserServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	 {
		String URL = request.getRequestURI();
		String html;
		if (URL.contains("url"))
		{		
			Properties params = ServletToolkit.parseURLParams(request);
			String userXML = "<user"+ getAttributeOrEmpty(params, "name")+">";
			userXML += "</user>";

			XMLMediator.addUser(userXML);

			ServletToolkit.writeResponse(response, userXML);
		}
		else
		{	
			String XSLPath = "resources/xsl/common/create_user.xsl";
			String fluxXML = "<noXML/>";
			Map<String, String> xslParams = new HashMap<String, String>();
			xslParams.put("pageTitle", "Ajout utilisateur");
			xslParams.put("htmlBody", "Utilisateur à ajouter");
			html = XMLToolkit.transformXML(fluxXML, XSLPath, xslParams);
			ServletToolkit.writeResponse(response, html);
		}
	}
	
	/*** Methode ajoutée */
	protected String getAttributeOrEmpty(Properties params, String k) 
	{
		return params.containsKey(k) ? " " + k + "=\"" + (params.getProperty(k)) + "\"" : "";
	}

}
